package com.example.controller;

import com.example.entity.Adminuser;
import com.example.service.AdminuserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginCtrl {
    //@Autowired
    @Resource
    AdminuserService adminuserService;

    @GetMapping("/toLoginPage")
    public String Login() {
        return "Login";
    }

//    @PostMapping("/first")
//    public String doLogin(String aduname,String adupwd){
//        System.out.println(aduname + "---------" + adupwd);
//        return "first";
//    }

//    @PostMapping("/first")
//    public String doLogin(Adminuser adminuser){
//        System.out.println("进行登录处理" + adminuser.getAduname()+"  "+adminuser.getAdupwd());
//
//        Adminuser admin =  adminuserService.findAdmin(adminuser);
//        System.out.println(admin);
//        return "first";
//    }

//    @PostMapping("/first")
//    public String doLogin(Adminuser adminuser, Model model) {
//        Adminuser admin = adminuserService.findAdmin(adminuser);
//
//        if (admin == null) {
//            model.addAttribute("msg", "用户民或者密码错误！");
//            return "login";
//        } else {
//            return "first";
//        }
//    }
        @PostMapping("/dologin")
        public String doLogin(Adminuser adminuser, Model model,HttpSession session) {
            System.out.println(DigestUtils.md5DigestAsHex(adminuser.getAdupwd().getBytes()));
            adminuser.setAdupwd( DigestUtils.md5DigestAsHex(adminuser.getAdupwd().getBytes()));
            Adminuser admin = adminuserService.findAdmin(adminuser);

            if (admin == null) {
                model.addAttribute("msg", "用户民或者密码错误！");
                return "login";
            }
            else {
                session.setAttribute("aduName",admin.getAduname());
                return "redirect:/admin/goods";
            }
        }

        @GetMapping("/logout")
        public String doLogout(HttpSession session, SessionStatus sessionStatus){
        // 只是让session失效 但session仍然存在
        session.invalidate();
        sessionStatus.setComplete();
        return "login";
    }

}
//redirect 重定向
